package com.onlyMe.world.components.inventory
{
	import com.onlyMe.world.components.base.BaseIsleComponent;
	import com.onlyMe.world.objects.IsleObject;
	import com.onlyMe.world.objects.IsleObjectContext;
	import com.qb9.flashlib.utils.ArrayUtil;
	
	/**
	 * @author ariel
	 */
	public final class InventoryComponent extends BaseIsleComponent implements IsleObjectContext
	{
		private var _objects:Array = [];
		private var _maxWeight:Number;
		
		public function InventoryComponent()
		{
		}

		//-- Deserialization
		
		override public function deserialize(xml:XML):void
		{
			super.deserialize(xml);
			_maxWeight = xml.@maxWeight;
		}
		
		//-- Utils
		
		private function event(type:String, object:IsleObject=null):void
		{
			object.dispatchEvent(new InventoryComponentEvent(type, object));
		}
		
		//-- IsleObjectContext implementation
		
		public function has(object:IsleObject):Boolean
		{
			return ArrayUtil.contains(_objects, object);
		}
		
		public function add(object:IsleObject):void
		{
			if (has(object)) return;
			
			_objects.push(object);
			event(InventoryComponentEvent.OBJECT_ADDED, object);
		}
		
		public function remove(object:IsleObject):void
		{
			if (!has(object)) return;
			
			ArrayUtil.removeElement(_objects, object);
			event(InventoryComponentEvent.OBJECT_REMOVED, object);
		}
		
		//-- Exposed getters
		
		public function get maxWeight():Number
		{
			return _maxWeight;
		}
		
		public function get mappedObjects():Object
		{
			var data:Object = { };
			for each (var object:IsleObject in _objects)
			{
				var type:String = object.type;
				if (type in data)
					data[type].push(object);
				else
					data[type] = [object];
			}
			return data;
		}
		
		public function get objects():Array
		{
			return _objects.concat();
		}
	}

}
